<template>
  <PageLayout class="form-container">
    <a-card>
      <div class="form-title">{{ route.query.id ? "编辑" : "新增" }}角色</div>
      <div class="form-box w-600">
        <a-form :model="formState" :rules="rules" ref="formRef" layout="Vertical" :labelCol="{ style: { width: '80px' } }" :wrapperCol="{ style: { width: 'calc(100% - 80px)' } }">
          <a-form-item label="角色名称" name="roleName" required>
            <a-input v-model:value="formState.roleName" placeholder="请输入角色名称" :maxlength="50" />
          </a-form-item>
          <a-form-item label="角色权限" name="menuIds">
            <!-- <a-select
              v-model:value="formState.menuIds"
              placeholder="请选择角色权限"
              :options="deptOptions"
            /> -->
            <a-tree-select v-model:value="formState.menuIds" style="width: 100%" :tree-data="treeData" tree-checkable showCheckedStrategy="SHOW_ALL" allow-clear placeholder="请选择角色权限" tree-node-filter-prop="label" />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea v-model:value="formState.remark" placeholder="请输入" :options="options" :maxlength="300" />
          </a-form-item>
          <a-button type="primary" class="float-right" style="width: 100px" @click="save">保存</a-button>
        </a-form>
      </div>
    </a-card>
  </PageLayout>
</template>

<script setup>
import { postRoleAdd, postRoleUpdate, postRoleDetail } from "@/api/common";
import { postMenuTreeList } from "@/api/system";
import { useStoreCommonEnum } from "@/store";
import { message } from "ant-design-vue";
import { onMounted } from "vue";
import list from "./test.js";
import { flatMapDeep } from "lodash";
const storeCommonEnum = useStoreCommonEnum();

const route = useRoute();
const router = useRouter();
const formRef = ref(null);

const formState = reactive({
  id: "",
  roleName: "",
  isAdmin: 0,
  orderNum: 0,
  menuIds: undefined,
  remark: "",
});
const treeData = ref([]);

function resetTreeData(tree) {
  let resultTree = [];
  tree.forEach((item) => {
    let btnList = item.childrenList?.filter((ele) => {
      return ele.menuType == "F";
    });
    let curComponent = {
      ...item,
      // children: item.childrenList,
      label: item.menuName,
      value: item.id,
      btnList,
    };
    console.log("curComponent", curComponent);
    curComponent.children = resetTreeData(item.childrenList);
    resultTree.push(curComponent);
  });

  return resultTree;
}

function flattenArray(arr) {
  let result = [];
  arr.forEach(item => {
    result.push(item);
    if (item.children && Array.isArray(item.children)) {
      result = result.concat(flattenArray(item.children));
    }
  });

  return result;
}

const treeDataList = ref([])
onMounted(async () => {
  console.log('list', list);
  // treeData.value = JSON.parse(JSON.stringify(resetTreeData(list.data)));
  postMenuTreeList().then((res) => {
    treeData.value = JSON.parse(JSON.stringify(resetTreeData(res.data)));
    treeDataList.value = flattenArray(treeData.value)

    if (route.query.id) {
      postRoleDetail({ id: route.query.id }).then((res1) => {
        for (let key in formState) {
          formState[key] = res1.data[key];
        }
        let menuIds = [...formState.menuIds]
        // 重置一遍非全选子节点情况下过滤掉父节点，用于正常回显
        formState.menuIds = menuIds.filter(item => {
          const menuItem = treeDataList.value.find(ele => ele.id == item)
          if (menuItem.children) {
            const childrenList = flattenArray(menuItem.children)
            return childrenList.every(child => menuIds.includes(child.id))
          } else {
            return true
          }

        })
      });
    }
  });

});

const rules = {
  roleName: [{ required: true, message: "请输入用户名/姓名", trigger: "blur" }],
  username: [{ required: true, message: "请输入账号/邮箱", trigger: "blur" }],
  // menuIds: [{ required: true, message: "请选择部门", trigger: "blur" }],
};
// 获取非全选情况下父节点的值
const getTrueMenuIds = () => {
  const list = []
  let getParentId = (id) => {
    let data = treeDataList.value.find(obj => obj.id == id)
    if (data.parentId != 0 && list.every(ele => data.parentId != ele)) {
      list.push(data.parentId)
      let parentData = treeDataList.value.find(obj => obj.id == data.parentId)
      if (parentData) {
        getParentId(parentData.id)
      }
    }
  }
  formState.menuIds.map(item => {
    getParentId(item)
  })
  return list

}
const save = () => {


  formRef.value.validate().then(() => {
    const obj = {
      ...formState,
      // menuIds: [...formState.menuIds, ...getTrueMenuIds()]
      menuIds: Array.from(new Set([...formState.menuIds, ...getTrueMenuIds()]))
    }
    const requestUrl = formState.id ? postRoleUpdate : postRoleAdd;
    requestUrl(obj).then(() => {
      message.success(formState.id ? "编辑成功" : "新增成功");
      storeCommonEnum.getCommonEnum("role", true);
      router.go(-1);
    });
  });
};

</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 24px;
  margin-left: 130px;
  :deep(.ant-btn) {
    margin-right: 16px;
  }
}
</style>
